package ru.lukyanets.transmission.client.action;

import com.google.inject.Inject;
import javafx.event.ActionEvent;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import ru.lukyanets.transmission.client.app.PrimaryStage;
import ru.lukyanets.transmission.client.util.DialogUtil;

import com.google.inject.Singleton;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;

/**
 * @author slukyanets
 */
@Singleton
public class AddTorrentUrlAction extends AddTorrentAction {
    private static final HttpClient HTTP_CLIENT = HttpClients.createDefault();

    /** @noinspection unused*/
    @Inject
    @PrimaryStage
    private Stage primaryStage;

    public AddTorrentUrlAction() {
        setAccelerator(new KeyCodeCombination(KeyCode.A, KeyCombination.ALT_DOWN));
    }

    @Override
    protected void performAction(ActionEvent event) {
        Dialog<ButtonType> dlg = new Dialog<>();
        dlg.initOwner(primaryStage);
        dlg.setTitle("Add torrent link");
        dlg.setResizable(false);
        dlg.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
        dlg.initStyle(StageStyle.UTILITY);
        final TextField textField = new TextField();
        dlg.getDialogPane().setContent(DialogUtil.buildInputContent(textField, "URL of .torrent file"));

        Optional<ButtonType> result = dlg.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            InputStream stream = downloadTorrent(textField.getText());
            if (stream != null) {
                addTorrent(stream);
            }
        }
    }

    private static InputStream downloadTorrent(String urlString) {
        try {
            URI uri = new URI(urlString);
            return HTTP_CLIENT.execute(new HttpGet(uri), response -> response.getEntity().getContent());
        } catch (URISyntaxException e) {
            DialogUtil.showError("Invalid URL format");
        } catch (IOException e) {
            DialogUtil.showError("Can't download file");
        }
        return null;
    }
}
